<template>
  <div class="login">
    <router-link :to="{ name: 'Home' }"
      ><img src="../assets/3.png" alt="" class="logo"
    /></router-link>
    <van-form @submit="onSubmit">
      <van-field
        v-model="userName"
        name="userName"
        label="用户名"
        placeholder="用户名"
        :rules="[{ required: true, message: '请填写用户名' }]"
      />
      <van-field
        v-model="password"
        type="password"
        name="password"
        label="密码"
        placeholder="密码"
        :rules="[{ required: true, message: '请填写密码' }]"
      />
      <div style="margin: 16px;">
        <van-button round block type="info" native-type="submit"
          >登录</van-button
        >
      </div>
    </van-form>
    <router-link :to="{ name: 'Reg' }" style="float:right;margin:16px">
      没有账号，我要注册
    </router-link>
  </div>
</template>

<script>
import { Toast } from "vant";
import { loginAPI } from "../services/auth";
import { setToken } from "../utils/tools";
export default {
  name: "login",
  data() {
    return {
      userName: "",
      password: "",
    };
  },
  methods: {
    async onSubmit(values) {
      const res = await loginAPI(values);
      if (res.code === 1) {
        setToken(res.data);
        Toast.success("登录成功");

        this.$router.replace({ name: "User" });
        //登录成功后获取购物车数量
        this.$eventBus.$emit("updateCartCount");
      } else {
        Toast.fail(res.data);
      }
    },
  },
};
</script>

<style lang="scss" scoped></style>
